import { computed } from 'vue'
import { useUserStore } from '@/stores/user'

const normalizePermission = (permission: string | undefined | null): string => {
  if (!permission) return ''

  const trimmed = permission.trim()
  if (!trimmed) return ''

  if (trimmed === '*') {
    return '*'
  }

  const upper = trimmed.toUpperCase()
  if (upper === 'ADMIN') {
    return '*'
  }

  if (trimmed.includes(':')) {
    return trimmed.toLowerCase()
  }

  const lower = trimmed.toLowerCase()
  const firstUnderscoreIndex = lower.indexOf('_')

  if (firstUnderscoreIndex === -1) {
    return lower
  }

  const module = lower.slice(0, firstUnderscoreIndex)
  const action = lower.slice(firstUnderscoreIndex + 1)
  return `${module}:${action}`
}

export function usePermission() {
  const userStore = useUserStore()

  const permissionSet = computed(() => {
    const set = new Set<string>()

    const permissions = Array.isArray(userStore.permissions) ? userStore.permissions : []
    permissions.forEach((perm) => {
      if (!perm) return
      set.add(perm)

      const lower = perm.toLowerCase()
      set.add(lower)

      const upper = perm.toUpperCase()
      set.add(upper)

      const normalized = normalizePermission(perm)
      if (normalized) {
        set.add(normalized)
        set.add(normalized.toUpperCase())
      }
    })

    return set
  })

  const hasPermission = (permission: string | string[]) => {
    const set = permissionSet.value
    if (set.has('*')) return true

    const check = (perm: string) => {
      if (!perm) return false
      const normalized = normalizePermission(perm)
      return (
        set.has(perm) ||
        set.has(perm.toLowerCase()) ||
        set.has(perm.toUpperCase()) ||
        (normalized ? set.has(normalized) || set.has(normalized.toUpperCase()) : false)
      )
    }

    if (Array.isArray(permission)) {
      return permission.some(check)
    }

    return check(permission)
  }

  const hasRole = (role: string | string[]) => {
    if (Array.isArray(role)) {
      return role.some(r => userStore.roles.includes(r))
    }

    return userStore.roles.includes(role)
  }

  const hasAnyPermission = (permissions: string[]) => {
    return permissions.some(permission => hasPermission(permission))
  }

  const hasAllPermissions = (permissions: string[]) => {
    return permissions.every(permission => hasPermission(permission))
  }

  const isAdmin = computed(() => {
    return hasRole('admin')
  })

  const isManager = computed(() => {
    return hasRole(['admin', 'manager'])
  })

  const isDeveloper = computed(() => {
    return hasRole(['admin', 'manager', 'developer'])
  })

  const isTester = computed(() => {
    return hasRole(['admin', 'manager', 'tester'])
  })

  const isUiDesigner = computed(() => {
    return hasRole(['admin', 'manager', 'ui_designer'])
  })

  const isViewer = computed(() => {
    return hasRole(['admin', 'manager', 'developer', 'tester', 'ui_designer', 'viewer'])
  })

  return {
    hasPermission,
    hasRole,
    hasAnyPermission,
    hasAllPermissions,
    isAdmin,
    isManager,
    isDeveloper,
    isTester,
    isUiDesigner,
    isViewer
  }
}
